import React, { Component } from 'react';
import styles from './index.module.scss';
import classNames from 'classnames';
import { update } from '@/utils/immutableUtil';
import { withConsumer } from '../../../context';

@withConsumer
class Comp extends Component {
  iframeRef = React.createRef();
  state = {
    iframeKey: '',
    selectedElement: null,
    textContent: '',
  };

  componentDidMount() {
    const {
      value: { event },
    } = this.props;
    window.addEventListener('message', this.handleIframeMessage);
    event.on(`pptTextUpdate-${this.props.index}`, this.pptTextUpdate);
  }

  componentWillUnmount() {
    window.removeEventListener('message', this.handleIframeMessage);
  }

  componentDidUpdate(prevProps) {
    // If edit mode changed, update the iframe content
    if (prevProps.editMode !== this.props.editMode) {
      this.setupIframeForEditing();
    }
  }

  calculateScale = () => {
    const { data, containerWidth } = this.props;

    // iframe 原始尺寸
    const targetWidth = data.width;
    const targetHeight = data.height;
    // 宽高比
    const aspectRatio = targetWidth / targetHeight;

    // 根据宽高比计算容器高度
    const containerHeight = containerWidth / aspectRatio;

    // 计算缩放值
    const scale = containerWidth / targetWidth;

    return {
      scale,
      containerHeight: containerHeight,
    };
  };

  setupIframeForEditing = () => {
    const iframe = this.iframeRef.current;
    if (!iframe || !iframe.contentWindow) return;

    setTimeout(() => {
      try {
        const { editMode, index } = this.props;

        // 移除之前的事件监听器（如果存在）
        if (iframe.contentWindow.editModeClickHandler) {
          iframe.contentDocument.removeEventListener(
            'click',
            iframe.contentWindow.editModeClickHandler,
            true,
          );
          iframe.contentWindow.editModeClickHandler = null;
        }

        if (editMode) {
          // 创建新的点击处理函数
          iframe.contentWindow.editModeClickHandler = function (e) {
            if (!e.target || !e.target.closest('body')) return;

            // 阻止默认行为
            e.preventDefault();
            e.stopPropagation();

            // 先清除所有选择 - 使用iframe的contentDocument而不是document
            const allElements = iframe.contentDocument.querySelectorAll(
              '.cascade-selected-element',
            );
            allElements.forEach((el) => {
              el.classList.remove('cascade-selected-element');
              el.style.outline = '';
            });

            // 添加选择样式到当前点击的元素
            e.target.classList.add('cascade-selected-element');
            e.target.style.outline = '2px solid #1890ff';

            // 存储选中的文本
            window.selectedText = e.target.textContent;

            // 临时移除 outline 样式以获取干净的 outerHTML
            const originalOutline = e.target.style.outline;
            e.target.style.outline = '';
            const cleanOuterHTML = e.target.outerHTML;
            e.target.style.outline = originalOutline;

            // 发送消息到父窗口
            window.parent.postMessage(
              {
                type: `elementSelected-${index}`,
                text: e.target.textContent,
                tagName: e.target.tagName,
                elementId: Date.now(), // 添加唯一ID以便跟踪
                domString: cleanOuterHTML, // 添加不含 outline 样式的 DOM 元素字符串表示
              },
              '*',
            );
          };

          // 添加点击事件监听器
          iframe.contentDocument.addEventListener(
            'click',
            iframe.contentWindow.editModeClickHandler,
            true,
          );

          // 添加选择样式
          const style = document.createElement('style');
          style.textContent = '.cascade-selected-element { cursor: pointer; }';
          iframe.contentDocument.head.appendChild(style);

          // toast.success('编辑模式已开启，点击元素进行编辑');
        } else {
          // 移除选择样式
          const elements = iframe.contentDocument.querySelectorAll(
            '.cascade-selected-element',
          );
          elements.forEach((el) => {
            el.classList.remove('cascade-selected-element');
            el.style.outline = '';
          });

          // 移除添加的样式表
          const styleElements =
            iframe.contentDocument.head.querySelectorAll('style');
          styleElements.forEach((el) => {
            if (el.textContent.includes('cascade-selected-element')) {
              el.remove();
            }
          });

          this.setState({
            selectedElement: null,
            textContent: '',
          });

          // toast.info('已退出编辑模式');
        }
      } catch (error) {
        console.error('Error setting up iframe for editing:', error);
      }
    }, 500); // Give iframe time to load
  };

  handleIframeMessage = (event) => {
    const {
      index,
      value: { changeState },
    } = this.props;
    if (event.data && event.data.type === `elementSelected-${index}`) {
      console.log(`elementSelected-${index}`, event.data);

      this.setState({
        selectedElement: event.data,
        textContent: event.data.text,
      });

      // 判断是否为常见的文字类型标签
      const tagName = event.data.tagName;
      const textTags = [
        // 标题标签
        'H1',
        'H2',
        'H3',
        'H4',
        'H5',
        'H6',
        // 段落和文本标签
        'P',
        'SPAN',
        'STRONG',
        'EM',
        'B',
        'I',
        'U',
        // 列表项
        'LI',
        // 其他可能包含文本的标签
        'A',
        'BUTTON',
        'LABEL',
        'CAPTION',
        'FIGCAPTION',
        // 表格相关
        'TH',
        'TD',
      ];

      // 如果是文本类型的标签，打开文本编辑器
      if (textTags.includes(tagName)) {
        var pptSetTextData = {
          ...event.data,
          index: index,
        };
        changeState({
          pptSetBoxOpen: false,
          pptSetTextOpen: true,
          pptSetTextData: pptSetTextData,
        });
      } else {
        changeState({
          pptSetBoxOpen: true,
          pptSetTextOpen: false,
          pptSetTextData: pptSetTextData,
        });
      }
    }
  };

  handleTextChange = (e) => {
    this.setState({ textContent: e.target.value });
  };

  applyTextChange = (html) => {
    const { list, index } = this.props;
    var dom = html;

    // Update the element in the iframe
    try {
      const iframe = this.iframeRef.current;
      if (iframe && iframe.contentDocument) {
        // 确保只更新当前选中的元素
        const selectedEl = iframe.contentDocument.querySelector(
          '.cascade-selected-element',
        );
        if (selectedEl) {
          selectedEl.innerHTML = dom;
          // 修改后的完整 HTML 代码
          list[index].newCode =
            iframe.contentDocument.documentElement.outerHTML;
          console.log(list);
        }
      }
    } catch (error) {
      console.error('Error updating element text:', error);
    }
  };

  pptTextUpdate = (data) => {
    this.applyTextChange(data.html);
  };

  // 清除所有选择状态的辅助方法
  clearSelection = (iframe) => {
    if (!iframe || !iframe.contentDocument) return;

    const selectedElements = iframe.contentDocument.querySelectorAll(
      '.cascade-selected-element',
    );
    selectedElements.forEach((el) => {
      el.classList.remove('cascade-selected-element');
      el.style.outline = '';
    });
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    const { iframeKey } = this.state;
    const { data, editMode } = this.props;

    var obj = this.calculateScale();

    // 假设容器宽度为 100%，根据宽高比计算高度
    let containerStyle = {
      position: 'relative',
      width: '100%',
      height: obj.containerHeight + 'px',
      overflow: 'hidden',
    };

    const iframeStyle = {
      width: data.width + 'px',
      height: data.height + 'px',
      transformOrigin: 'left top',
      overflow: 'hidden',
      display: 'block',
      border: 'none',
      position: 'absolute',
      transform: `scale(${obj.scale})`,
    };

    return (
      <div className={styles.fragmentContainer}>
        <div
          className={classNames([
            styles.iframe,
            editMode ? styles.editMode : '',
          ])}
          style={containerStyle}
        >
          <iframe
            ref={this.iframeRef}
            key={iframeKey}
            srcdoc={data.code}
            style={iframeStyle}
            sandbox="allow-same-origin allow-scripts"
          />
        </div>
      </div>
    );
  }
}

export default Comp;
